# !/usr/bin/env python3
import os,json,time
import sys, hashlib
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from openapi_client.api import fileupload_api
import openapi_client,requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

from urllib.parse import quote,unquote

ShareThirdId = 2138
ShareSecret = 'c8892620'
# access_token = "121.2335d73fd9a8d580665aaa73c8861123.YaQfV_fgjOFFdZv6-qhg6iE_PcDrNHZP1_FH0SD.5-k6pw"
access_token = "123.ef3b19708c1a0c41bc9fb68e51b12e45.YmIf6yUV3bLbqi5GySax15SNJjLK5Inn4dRoulx.AixJfA"

def precreate(access_token, path, block_list, isdir, size):
    with openapi_client.ApiClient() as api_client:
        api_instance = fileupload_api.FileuploadApi(api_client)
        autoinit = 1  # int | autoinit
        rtype = 3  # int | rtype (optional)
        try:
            api_response = api_instance.xpanfileprecreate(
                access_token, path, isdir, size, autoinit, block_list, rtype=rtype)
            return api_response
        except openapi_client.ApiException as e:
            print("Exception when calling FileuploadApi->xpanfileprecreate: %s\n" % e)
            return False

def upload(access_token, partseq, path, uploadid, cache_file):
    """
    upload
    """
    # Enter a context with an instance of the API client
    with openapi_client.ApiClient() as api_client:
        # Create an instance of the API class
        api_instance = fileupload_api.FileuploadApi(api_client)
        type = "tmpfile"  # str |
        try:
            file = open(cache_file, 'rb') # file_type | 要进行传送的本地文件分片
        except Exception as e:
            print("Exception when open file: %s\n" % e)

        # example passing only required values which don't have defaults set
        # and optional values
        try:
            api_response = api_instance.pcssuperfile2(
                access_token, partseq, path, uploadid, type, file=file)
            return api_response
        except openapi_client.ApiException as e:
            print("Exception when calling FileuploadApi->pcssuperfile2: %s\n" % e)
            return False

def create(access_token, path, isdir, size, uploadid, block_list):
    """
    create
    """
    # Enter a context with an instance of the API client
    with openapi_client.ApiClient() as api_client:
        # Create an instance of the API class
        api_instance = fileupload_api.FileuploadApi(api_client)
        rtype = 3  # int | rtype (optional)

        # example passing only required values which don't have defaults set
        # and optional values
        try:
            api_response = api_instance.xpanfilecreate(
                access_token, path, isdir, size, uploadid, block_list, rtype=rtype)
            return api_response
        except openapi_client.ApiException as e:
            print("Exception when calling FileuploadApi->xpanfilecreate: %s\n" % e)
            return False

def share(fd_id, access_token):
    fid_list = json.dumps([1123302711156158,522635225295698,987644131881555,fd_id])
    schannel = 4
    period = 0
    third_type = ShareThirdId
    csign = hashlib.md5((str(ShareThirdId) + fid_list + str(schannel) + ShareSecret).encode('gbk')).hexdigest()
    url = "https://pan.baidu.com/rest/2.0/xpan/share/set"
    querystring = {"access_token": access_token}

    m = MultipartEncoder({'fid_list':fid_list,'schannel':str(schannel),'period':str(period),'third_type':str(third_type),'csign':csign})
    headers = {
        'Content-Type': m.content_type
    }
    result = requests.request("POST", url, data=m, headers=headers, params=querystring)
    if result.status_code != 200:
        return False
    return json.loads(result.content)

def download(dlink):
    url = dlink+"&access_token="+access_token

    payload = {}
    files = {}
    headers = {
        'User-Agent': 'pan.baidu.com'
    }

    result = requests.request("GET", url, headers=headers, data=payload, files=files)
    print(result.content)
    exit()
    if result.status_code != 200:
        return False
    return json.loads(result.content)

def get_file(access_token, dirname='/', key=''):

    url = "http://pan.baidu.com/rest/2.0/xpan/file?dir="+dirname+"&access_token="+access_token+"&web=1&recursion=1&page=1&num=2&method=search&key="+key

    payload = {}
    files = {}
    headers = {
        'User-Agent': 'pan.baidu.com'
    }
    result = requests.request("GET", url, headers=headers, data=payload, files=files)
    if result.status_code != 200:
        return False
    return json.loads(result.content)

def file_detail(fsids):
    url = "http://pan.baidu.com/rest/2.0/xpan/multimedia?method=filemetas&access_token="+access_token+"&fsids="+fsids+"&thumb=1&dlink=1&extra=1"

    payload = {}
    files = {}
    headers = {
        'User-Agent': 'pan.baidu.com'
    }

    result = requests.request("GET", url, headers=headers, data=payload, files=files)
    if result.status_code != 200:
        return False
    return json.loads(result.content)

#分享提取码验证
def get_share(surl, pwd):
    url = "https://pan.baidu.com/rest/2.0/xpan/share"
    querystring = {"method": "verify", "surl": surl}

    m = MultipartEncoder({"pwd":pwd, "third_type":str(ShareThirdId),"redirect":str(1)})
    headers = {
        'Content-Type': m.content_type,
        'Referer': "pan.baidu.com",
        'cache-control': "no-cache",
        'Postman-Token': "68b9fce6-51dd-4935-b634-24b59743f6e5"
    }
    result = requests.request("POST", url, data=m, headers=headers, params=querystring)
    if result.status_code != 200:
        return False
    return json.loads(result.content)

#查询分享详情
def get_share_detail(shorturl, spd):
    url = "https://pan.baidu.com/api/shorturlinfo"

    querystring = {'shorturl': shorturl,"spd": spd}

    payload = ""
    headers = {
        'cache-control': "no-cache",
        'Postman-Token': "c5baffc2-81a0-44fe-b24a-8f60964d1f91"
    }

    result = requests.request("GET", url, data=payload, headers=headers, params=querystring)
    if result.status_code != 200:
        return False
    return json.loads(result.content)

#获取分享文件信息
def get_share_info(sekey, uk, shareid):
    url = "https://pan.baidu.com/rest/2.0/xpan/share"

    querystring = {"method": "list", "shareid":shareid , "uk": uk, "page": "1", "num": "100","root": "1", "fid": "", "sekey": sekey, "fid\t": ""}

    payload = ""
    headers = {
        'cache-control': "no-cache",
        'postman-token': "17af71b1-0ce7-1c20-6ea1-a2ffccf1bbee"
    }

    result = requests.request("GET", url, data=payload, headers=headers, params=querystring)

    if result.status_code != 200:
        return False
    return json.loads(result.content)

#分享文件转存
def share_file_save(shareid, fromId, sekey, fsidlist):
    url = "https://pan.baidu.com/rest/2.0/xpan/share"
    querystring = {"method":"transfer","access_token":access_token,"shareid":shareid,"from":fromId,"sekey": sekey}
    print(querystring)
    m = MultipartEncoder({"fsidlist":fsidlist, "path":"/common","async":'0',"ondup":"newcopy"})
    headers = {
        'Content-Type': m.content_type,
        'User-Agent': "pan.baidu.com",
        'Referer': "pan.baidu.com",
        'cache-control': "no-cache",
        'Postman-Token': "2756bf0a-adbe-46fe-a305-a84a706052b3"
    }
    result = requests.request("POST", url, data=m, headers=headers, params=querystring)
    if result.status_code != 200:
        return False
    return json.loads(result.content)

def baidu_file(id, path ,file_path, is_split):
    try:
        path = 'mixkit/' + path + '/' + file_path.split('/')[-1]
        exsis_file_result = get_file(access_token, path, file_path)
        if exsis_file_result:
            isdir = 0  # 是否目录，0 文件、1 目录
            size = os.path.getsize(file_path)
            file_dir = os.path.dirname(file_path)+'/'
            files = os.listdir(file_dir)
            cache_file_list = []
            md5_file_list = []
            for f in files:
                if f.find(id+'_') != -1 and is_split==1:
                    cache_file_list.append(f)
                if is_split==0 and f.find(id+'_') == -1:
                    cache_file_list.append(f)

            cache_file_list.sort()
            for mdv in cache_file_list:
                try:
                    file = open(file_dir + mdv, 'rb')  # file_type | 要进行传送的本地文件分片
                    md5_file_list.append(hashlib.md5(file.read()).hexdigest().lower())
                except Exception as e:
                    print("Exception when open file: %s\n" % e)

            pre_result = precreate(access_token, path, json.dumps(md5_file_list), isdir, size)
            if pre_result == False:
                raise Exception('预上传失败')
            if pre_result['errno'] != 0:
                raise Exception('预上传失败'+pre_result['show_msg'])


            # #分片上传
            i = 0
            for mdv_path in cache_file_list:
                upload_result = upload(access_token, str(i), path, pre_result['uploadid'], file_dir+mdv_path)
                if upload_result == False:
                    raise Exception('切片上传失败')
                i+=1

            result = create(access_token, path, isdir, size, pre_result['uploadid'], json.dumps(md5_file_list))
            if result == False:
                raise Exception('上传失败')
            if result['errno'] != 0:
                raise Exception('上传失败'+result['show_msg'])
            fs_id = result['fs_id']
        else:
            fs_id = exsis_file_result
        #创建分享链接
        share_result = share(fs_id, access_token)
        if share_result == False:
            raise Exception('创建分享链接失败')
        if share_result['errno'] != 0:
            raise Exception('创建分享链接失败'+share_result['show_msg'])

        return share_result
    except openapi_client.ApiException as e:
        # return baidu_file(id, path ,file_path)
        print('上传失败')

if __name__=='__main__':
    # result = get_file(access_token, '/mixkit/video', 'mixkit-garbage-on-the-seashore-3031.mp4')
    # print(result)
    # exit()
    # if result['errno'] == 0:
    #     fs_ids = [v['fs_id'] for v in result['list']]
    #     file_detail_result = file_detail(json.dumps(fs_ids))
    #     if file_detail_result['errno'] == 0:
    #         print(download(file_detail_result['list'][0]['dlink']))
    #         'https://pan.baidu.com/share/init?surl=1LGoTs9DgEYmyMQ7khOFVQ  '
    #         'https://pan.baidu.com/s/11LGoTs9DgEYmyMQ7khOFVQ'

    # get_share_result = get_share('1LGoTs9DgEYmyMQ7khOFVQ', '3m8r')
    # print(get_share_result)
    # print(unquote('qjuebJuhx5uxlWa6mEvqCncelLyza%2BhwVVFixltVUr4%3D'))
    # print('qjuebJuhx5uxlWa6mEvqCncelLyza+hwVVFixltVUr4=')
    # exit()

    #https://pan.baidu.com/s/1DjGZ8O9e3-IDby_Lve66mg?pwd=r832
    #1.分享提取码验证
    # get_share_result = get_share('DjGZ8O9e3-IDby_Lve66mg', 'r832')
    # print(get_share_result)
    # exit()
    #2.查询分享详情
    # print(unquote('xTB12X21ujO%2F1h5jl067yY34JWp0atlOoxPumLYex8U%3D'))
    # exit()
    # get_share_detail_result = get_share_detail('1DjGZ8O9e3-IDby_Lve66mg', 'xTB12X21ujO/1h5jl067yY34JWp0atlOoxPumLYex8U=')
    # print(get_share_detail_result)
    # exit()
    #3.获取分享文件信息
    # get_share_info_result = get_share_info('xTB12X21ujO/1h5jl067yY34JWp0atlOoxPumLYex8U=', 1446173441, 3229982729)
    # print(get_share_info_result)
    # exit()
    #4.分享转存
    # fsIds = json.dumps([603631123920485])
    # get_share_info_result = share_file_save(3229982729, 1446173441, 'xTB12X21ujO/1h5jl067yY34JWp0atlOoxPumLYex8U=', fsIds)
    # print(get_share_info_result)
    # exit()



    # get_share_result = get_share('NAGJ8crUtVAiMTwUdCWapg', 'r2ik', fsIds)
    # print(get_share_result)
    # exit()
    # print(unquote('kwfRAjNr6c9QOlShShWdorwhJxHFiADbzkh4laMKXNM%3D'))
    # get_share_detail_result = get_share_detail('1NAGJ8crUtVAiMTwUdCWapg', unquote('kwfRAjNr6c9QOlShShWdorwhJxHFiADbzkh4laMKXNM%3D'))
    # print(get_share_detail_result)
    # exit()
    # get_share_info_result = get_share_info(unquote('kwfRAjNr6c9QOlShShWdorwhJxHFiADbzkh4laMKXNM%3D'), 1745639216, 3581657748)
    # print(get_share_info_result)
    # exit()
    fsIds = json.dumps([575376420284469])
    get_share_info_result = share_file_save(3581657748, 1745639216, unquote('kwfRAjNr6c9QOlShShWdorwhJxHFiADbzkh4laMKXNM%3D'), fsIds)
    print(get_share_info_result)
    exit()


    # print()
    # exit(quote("程序设计", 'utf-8'))
    # print(unquote('kwfRAjNr6c9QOlShShWdorwhJxHFiADbzkh4laMKXNM%3D'))
    # exit()
    # get_share_info_result = get_share_info('kwfRAjNr6c9QOlShShWdorwhJxHFiADbzkh4laMKXNM=')
    # print(get_share_info_result)
    # exit()


    # if get_share_result['errno'] == 0:
    #     get_share_detail_result = get_share_detail('qjuebJuhx5uxlWa6mEvqCncelLyza%2BhwVVFixltVUr4%3D')
    #     print(get_share_detail_result)
    #     exit()
    #
    #     print(get_share_detail_result)
    #     print(get_share_info(get_share_result['randsk'], get_share_detail_result['shareid'], get_share_detail_result['uk']))

    # print(share_file_save())
    # print(get_share_info())


